package com.pai4j.pgc.service.message;
import com.google.common.collect.Maps;
import com.pai4j.common.enums.RedisKeyEnum;
import com.pai4j.common.enums.community.ContentConfigEnum;
import com.pai4j.common.util.RedisUtil;
import com.pai4j.pgc.dao.community.IMessageTemplateDAO;
import com.pai4j.pgc.entity.community.MessageTemplateEntity;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.util.Map;

/**
 *
 *
 * @author: CYM-pai
 * @date: 2025/10/31 11:13
 **/
@Slf4j
@Service
public class MessageTemplateService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IMessageTemplateDAO messageTemplateDAO;


    /***
     * 获取模板配置
     * @param templateCode 模板CODE @see com.coder.common.enums.ContentConfigEnum
     * @param vars 变量值
     * @return
     */
    public String getContent(String templateCode, String ... vars) {
        String content = getMessageTemplateFromCache(templateCode);
        if (StringUtils.isBlank(content) || vars == null || vars.length == 0) {
            return content;
        }
        String[] configArgs = ContentConfigEnum.getVars(templateCode);
        if (configArgs == null || configArgs.length != vars.length) {
            log.error("content config get content error, args mismatch, templateCode:{}", templateCode);
            return "";
        }
        Map map = Maps.newHashMap();
        for (int i = 0; i < vars.length; i++) {
            map.put(configArgs[i], vars[i]);
        }
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
        StringTemplateLoader loader = new StringTemplateLoader();
        cfg.setTemplateLoader(loader);
        cfg.setClassicCompatible(true);
        loader.putTemplate(templateCode, content);
        try {
            Template template = cfg.getTemplate(templateCode);
            // 模版替换
            content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        } catch (Exception e) {
            log.error("content config get content error, templateCode:{}", templateCode, e);
        }
        return content;
    }

    private String getMessageTemplateFromCache(String templateCode) {
        String key = RedisKeyEnum.MESSAGE_CONTENT_TEMPLATE_CACHE.getKey();
        String template = redisUtil.hget(key, templateCode);
        if (StringUtils.isNotBlank(template)) {
            return template;
        }
        MessageTemplateEntity entity = messageTemplateDAO.findAllByCode(templateCode);
        redisUtil.hset(key, templateCode, entity.getTemplate(), RedisKeyEnum.MESSAGE_CONTENT_TEMPLATE_CACHE.getExpireTime());
        return entity.getTemplate();
    }
}
